﻿using System;
using System.Configuration;
using System.Web;
using System.Web.Configuration;
using System.Xml;

namespace Core
{
    public class WebConfigUtil
    {
        /// <summary>
        /// Changes the connection string authentication.
        /// </summary>
        /// <param name="connectionName">Name of the connection.</param>
        /// <param name="newDBUser">The new DB user.</param>
        /// <param name="newDBPassword">The new DB password.</param>
        /// <remarks>
        /// Don't forget to assign modify permission to ASPNET or NETWORK SERVICE user to access web.config file
        /// </remarks>
        public static void ChangeConnectionStringAuthentication(string connectionName, string newDBUser, string newDBPassword)
        {
            //Get Current configuration
            string user = string.Empty;
            string password = string.Empty;
            string currentConnectionString = WebConfigurationManager.ConnectionStrings[connectionName].ConnectionString;

            foreach (string item in currentConnectionString.Split(';'))
            {
                //Set User
                if (item.Contains("User ID"))
                {
                    user = item.Split('=')[1];
                }

                //Set Password
                if (item.Contains("Password"))
                {
                    password = item.Split('=')[1];
                }
            }

            //Save new configuration
            string newConnectionString = currentConnectionString;
            newConnectionString = newConnectionString.Replace("User ID=" + user, "User ID=" + newDBUser);
            newConnectionString = newConnectionString.Replace("Password=" + password, "Password=" + newDBPassword);

            Configuration webconfig = WebConfigurationManager.OpenWebConfiguration("~");

            webconfig.ConnectionStrings.ConnectionStrings[connectionName].ConnectionString = newConnectionString;

            webconfig.Save();
        }

        /// <summary>
        /// Encrypts the connection string.
        /// </summary>
        /// <remarks>
        /// Please add machinekey section under system.web section in your web.config before execute below method
        /// </remarks>
        public static void EncryptConnectionString()
        {
            Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
            ConfigurationSection section = config.GetSection("connectionStrings");
            if (!section.SectionInformation.IsProtected)
            {
                section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
                config.Save();
            }
        }

        /// <summary>
        /// Decrypts the connection string.
        /// </summary>
        /// <remarks>
        /// Please add machinekey section under system.web section in your web.config before execute below method
        /// </remarks>
        public static void DecryptConnectionString()
        {
            Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
            ConfigurationSection section = config.GetSection("connectionStrings");
            if (section.SectionInformation.IsProtected)
            {
                section.SectionInformation.UnprotectSection();
                config.Save();
            }
        }

        /// <summary>
        /// Refreshes the web application.
        /// </summary>
        public static void RefreshWebApplication()
        {
            try
            {
                WebConfigurationFileMap webConfig = new WebConfigurationFileMap();
                var vDir = HttpRuntime.AppDomainAppPath;
                foreach (VirtualDirectoryMapping v in webConfig.VirtualDirectories)
                {
                    if (v.IsAppRoot)
                    {
                        vDir = v.PhysicalDirectory;
                    }
                }

                XmlDocument doc = new XmlDocument();
                doc.Load(String.Concat(vDir, "web.config"));
                doc.Save(String.Concat(vDir, "web.config"));
            }
            catch
            {
            }
        }

        public static string GetADDomainAddress()
        {
            return WebConfigurationManager.AppSettings["ADDomainAddress"].ToString() ?? "LDAP://DC=kcc,DC=com";
        }
        public static string GetADDomainName()
        {
            return WebConfigurationManager.AppSettings["ADDomainName"].ToString() ?? "KC";
        }
    }
}
